<template>
  <div>
    <el-row class="lock-btn">
      <el-button-group>
        <!-- <el-button :disabled="userState" size="medium" type="primary" @click="refresh" round>刷新</el-button> -->
        <!-- <el-button :disabled="userState" size="medium" type="primary" @click="exportSCV" round>导出待开列表</el-button> -->
      </el-button-group>
      <el-select v-model="queryParams.status" placeholder="请选择发票状态">
        <el-option v-for="(status,index) in statusOptions" v-bind:key="index" :label="status" :value="index"></el-option>
      </el-select>
      
      <el-button-group>
        <el-input v-model="queryParams.name" auto-complete="off" placeholder="请输入发票抬头"></el-input>
      </el-button-group>
      <!-- <el-button :disabled="userState" size="medium" type="primary" @click="queryBtn" round>搜索</el-button> -->

      <br/>
      <el-date-picker
      :disabled="userState"
        v-model="queryParams.queryStartTime"
        value-format="yyyy-MM-dd HH:mm:ss"
        style="width: 215px;margin-top: 10px;margin-left:5px;"
        type="datetime"
        placeholder="请选择开始时间"
      ></el-date-picker>

       <el-date-picker
       :disabled="userState"
        v-model="queryParams.queryEndTime"
        value-format="yyyy-MM-dd HH:mm:ss"
        style="width:205px;"
        type="datetime"
        placeholder="请选择结束时间"
      
      ></el-date-picker>
      <el-button :disabled="userState" style="background:rgb(60, 186, 230);border:0;" size="medium" type="primary" @click="searchTime" round>查询</el-button>
      <el-button :disabled="userState" style="background-color: #67C23A;border:0;" size="medium" type="primary" @click="handleDownload" round>导出</el-button>
    </el-row>
    
    <el-row style="box-shadow: rgb(205 205 205) 1px 1px 8px;">
      <el-col :span="24">
        <el-table :header-cell-style="{ background: '#ecf3fd',color:'#000000' }" highlight-current-row  ref="invoiceProcTable" v-loading="loading" :data="invoiceProcs" :stripe="true" :row-key="'id'" :max-height="clientHeight" :height="clientHeight">
          <!-- <el-table-column type="selection" :reserve-selection="true" width="55" fixed></el-table-column> -->
          <!-- <el-table-column prop="id" label="申请开票ID" width="120" sortable></el-table-column> -->
          <el-table-column prop="titleId" label="抬头编号" width="240" sortable align="center"></el-table-column>
          <el-table-column prop="orderNo" label="订单编码" width="240" sortable align="center"></el-table-column>
          <el-table-column prop="status" label="发票状态" width="120" align="center">
            <template slot-scope="scope">
              <span>{{statusOptions[scope.row.status]}}</span>
            </template>
          </el-table-column>
          <el-table-column prop="type" label="发票类型" width="120" align="center">
            <template slot-scope="scope">
              <span>{{typeOptions[scope.row.type]}}</span>
            </template>
          </el-table-column>
          <el-table-column prop="name" label="抬头" width="200" sortable align="center"></el-table-column>
          <el-table-column prop="taxNo" label="税号" width="200" sortable  align="center"></el-table-column>
          <el-table-column prop="companyAddress" label="公司地址" width="240" sortable  align="center"></el-table-column>
          <el-table-column prop="companyPhoneNumber" label="公司电话" width="140" sortable  align="center"></el-table-column>
          <el-table-column prop="companyBank" label="公司账号银行名称" width="180" sortable  align="center"></el-table-column>
          <el-table-column prop="companyBankAccount" label="公司银行账户" width="240" sortable  align="center"></el-table-column>
          <el-table-column prop="recipientsEmail" label="收件人电子邮箱" width="200" sortable  align="center"></el-table-column>
          <el-table-column prop="recipientsMobileNumber" label="收件人手机号" width="180" sortable  align="center"></el-table-column>
          <el-table-column prop="applyTime" label="申请时间" width="200"  sortable  align="center"></el-table-column>
          <el-table-column prop="comments" label="备注" width="120" sortable  align="center"></el-table-column>
          <el-table-column label="操作" fixed="right" sortable  align="center">
            <template slot-scope="scope">
              <el-button :disabled="userState" class="operateBtn" size="primary" type="primary" @click="editBtn(scope.$index, scope.row)" title="修改申请">
                <i class="el-icon-edit-outline"></i>
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="24" class="page-tool">
        <el-pagination layout="total,sizes,prev, pager,next,jumper" :page-size="pageSize" :total="total" :page-sizes="[10, 20, 30, 40, 100]" @size-change="handlePageChange" @current-change="handleNoChange"></el-pagination>
      </el-col>
    </el-row>
    <el-dialog :title="dialogTitle" :visible.sync="editDialog" :width="'422px'">
      <el-form :model="editForm" :rules="rules" ref="editForm">
        <el-form-item label="抬头编号" :label-width="labelWidth" prop="titleId" >
          <el-input v-model="editForm.titleId" auto-complete="off" disabled></el-input>
        </el-form-item>
        <el-form-item label="发票状态" :label-width="labelWidth" prop="status">
          <el-select v-model="editForm.status" placeholder="请选择发票状态">
            <el-option v-for="(status,index) in statusOptions" v-bind:key="index" :label="status" :value="index"></el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="快递单号" :label-width="labelWidth" prop="expressNo">
          <el-input v-model="editForm.expressNo" auto-complete="off"></el-input>
        </el-form-item> -->
        <el-form-item label="备注" :label-width="labelWidth">
          <el-input v-model="editForm.comments" auto-complete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editDialog = false">取 消</el-button>
        <el-button type="primary" @click="submitEdit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { loadInvoiceProcApi, updateInvoiceApi, exportSCVApi,exportExcApi } from "../../api/invoice.js";
import { getNickName, getTestUserName,getRoleCode } from "../../util/auth";
import axios from "axios";
import { getToken } from "../../util/auth";

export default {
  data () {
    return {
      clientHeight:
        Math.max(
          document.documentElement.scrollHeight,
          document.body.scrollHeight
        ) -
        132 -
        5 +
        10 -
        28,
      statusOptions: ["未开票", "已申请开票", "已打印", "已寄出", "开票完成"],
      typeOptions: ["企业", "个人或政府事业单位"],
      loading: false,
      pageNo: 1,
      pageSize: 20,
      queryParams: {
        status: '',
        name: '',
        queryStartTime:'',
        queryEndTime:'',
        roleCode:''
      },
      total: 0,
      roleCode:'',
      invoiceProcs: [],
      labelWidth: "100px",
      dialogTitle: "",
      editForm: {},
      editDialog: false,

      rules: {
    
        status: [
            { required: true, message: '请选择发票状态', trigger: 'change' }
          ],
        titleId: [
            { required: true, message: '请选择发票状态', trigger: 'change' }
          ],
      },

      
    };
  },
  methods: {
    loadInvoiceProcs (pageNo, pageSize) {
      let _this = this;
      _this.loading = true;
      loadInvoiceProcApi({ pageNo: pageNo, pageSize: pageSize, status: _this.queryParams.status, name: _this.queryParams.name,queryStartTime: _this.queryParams.queryStartTime,queryEndTime: _this.queryParams.queryEndTime,roleCode:_this.roleCode})
        .then(resp => {
          _this.invoiceProcs = resp.data.dataList;
          _this.total = resp.data.totalNum;
          _this.loading = false;
        })
        .catch(e => {
          this.loaded = false;
          this.loading = false;
          
        });
    },
    handlePageChange (pageSize) {
      this.pageSize = pageSize;
      this.loadInvoiceProcs(this.pageNo, this.pageSize);
    },
    handleNoChange (pageNo) {
      this.pageNo = pageNo;
      this.loadInvoiceProcs(this.pageNo, this.pageSize);
    },
    refresh () {
      this.loadInvoiceProcs(this.pageNo, this.pageSize);
    },
    queryBtn () {
      let _this = this
      _this.loading = true
     
      this.loadInvoiceProcs(_this.pageNo, _this.pageSize);
    },

    searchTime() {
      let _this = this
      _this.loading = true
     var stime = new Date(this.queryParams.queryStartTime).getTime();
	   var etime = new Date(this.queryParams.queryEndTime).getTime();
	   var day = (etime - stime)/(24*60*60*1000);
    if (day <= 0) {
		alert("结束时间不能小于开始时间");
    _this.loading = false
   	}else{
    _this.loadInvoiceProcs(_this.pageNo, _this.pageSize);
    }

    },

handleDownload() {
  var _this = this;
  const exportParams = { pageNo:_this.pageNo, pageSize:_this.pageSize, status: _this.queryParams.status, name: _this.queryParams.name,queryStartTime: _this.queryParams.queryStartTime,queryEndTime: _this.queryParams.queryEndTime,roleCode:_this.roleCode};

  axios({
        method: "GET",
        url: "/lcinvoice/export",
        params:exportParams,
        headers: { pacargle: getToken() },
        responseType: "blob", //返回是个文件
      }).then((response) => {
        this.download(response); //then直接下载，方法在下边
      });

  // loadInvoiceProcApi({status: _this.queryParams.status, name: _this.queryParams.name,queryStartTime: _this.queryParams.queryStartTime,queryEndTime: _this.queryParams.queryEndTime})
  //      .then((response) => {
  //       this.download(response); //then直接下载，方法在下边
  //     });
    },
    download(res) {
      let blob = new Blob([res.data], { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,charset=UTF-8" }); //type是文件类，详情可以参阅blob文件类型
      // 创建新的URL并指向File对象或者Blob对象的地址
      const blobURL = window.URL.createObjectURL(blob);
      // 创建a标签，用于跳转至下载链接
      const tempLink = document.createElement("a");
      tempLink.style.display = "none";
      tempLink.href = blobURL;
      tempLink.setAttribute(
        "download",
        decodeURI(
          res.headers["content-disposition"].split(";")[1].split("=")[1]
        )
      );
      // 兼容：某些浏览器不支持HTML5的download属性
      if (typeof tempLink.download === "undefined") {
        tempLink.setAttribute("target", "_blank");
      }
      // 挂载a标签
      document.body.appendChild(tempLink);
      tempLink.click();
      document.body.removeChild(tempLink);
      // 释放blob URL地址
      window.URL.revokeObjectURL(blobURL);
    },
    exportSCV () {
  
        exportSCVApi().then(res => {

               let blob = new Blob([res.data], { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,charset=UTF-8" }); //type是文件类，详情可以参阅blob文件类型
              // 创建新的URL并指向File对象或者Blob对象的地址
              const blobURL = window.URL.createObjectURL(blob);
              // 创建a标签，用于跳转至下载链接
              const tempLink = document.createElement("a");
              tempLink.style.display = "none";
              tempLink.href = blobURL;
              tempLink.setAttribute(
                "download",
                decodeURI(
                  res.headers["content-disposition"].split(";")[1].split("=")[1]
                )
              );
              // 兼容：某些浏览器不支持HTML5的download属性
              if (typeof tempLink.download === "undefined") {
                tempLink.setAttribute("target", "_blank");
              }
              // 挂载a标签
              document.body.appendChild(tempLink);
              tempLink.click();
              document.body.removeChild(tempLink);
              // 释放blob URL地址
              window.URL.revokeObjectURL(blobURL);
 
        })
        .catch(e => {
          this.loaded = false;
          this.loading = false;
          console.log(e);
        });
    },
    editBtn (index, row) {
      let _this = this;
      _this.$nextTick(()=>{
        if(_this.$refs.editForm != undefined){
          _this.$refs.editForm.resetFields();
        }
      })
      _this.dialogTitle = "修改开票申请";
      _this.editForm = row;
  
      _this.loadInvoiceProcs();
      _this.editDialog = true;
    },
    submitEdit () {
      let _this = this;
      if(_this.queryParams.queryStartTime == '' || _this.queryParams.queryStartTime == null || _this.queryParams.queryEndTime == null || _this.queryParams.queryEndTime == ''){

                      this.$alert('请开始时间和结束时间！', '修改失败', {
                      confirmButtonText: '确定',});
                      return false
                  
      }
      _this.$refs.editForm.validate((valid) => {
        if (valid) {
          var editForm = {
          titleId: _this.editForm.titleId,
          status: _this.editForm.status,
          queryStartTime:_this.queryParams.queryStartTime,
          queryEndTime:_this.queryParams.queryEndTime
        };

        

        updateInvoiceApi(editForm)
          .then(resp => {
            console.log(editForm);
            _this.editDialog = false;
            if (resp.errmsg === "ok") {
              _this.loadInvoiceProcs();
              _this.$notify({
                title: "成功",
                message: "开票申请修改成功",
                type: "success"
              });
            } else {
              _this.$notify({
                title: "失败",
                message: "开票申请修改失败",
                type: "error"
              });
            }
          })
          .catch(e => {
            console.log(e);
            _this.$notify({
              title: "失败",
              message: "开票申请修改失败",
              type: "error"
            });
          });
        }
      });
    }
  },
  computed: {
    userState () {
      return getNickName() === getTestUserName();
    }
  },
  mounted: function () {
    this.roleCode = getRoleCode()
    this.$nextTick(function () {
      this.loadInvoiceProcs(this.pageNo, this.pageSize);
    });
  }
};
</script>
<style>


.page-tool div {
  text-align: right;
}

.lock-btn {
  margin-bottom: 5px;
  margin-top: -10px;
}
.operateBtn {
  font-size: 18px;
  width: 32px;
  height: 32px;
  padding: 0;
}
</style>
